package com.wobito.common.utils;

import com.alibaba.fastjson.JSON;
import com.wobito.common.constants.BusinessException;
import com.wobito.common.constants.ErrorCode;
import com.wobito.pojo.dto.user.LoginInfoDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;

@Slf4j
public class LoginInfoContext {

    //获取用户信息
    public static LoginInfoDTO getLogin(){
        try {
            //获取上下文
            SecurityContext context = SecurityContextHolder.getContext();
            if(context == null){
                return null;
            }
            Authentication authentication = context.getAuthentication();
            if(authentication == null){
                return null;
            }
            String principal = (String) authentication.getPrincipal();
            LoginInfoDTO loginInfoDto = JSON.parseObject(principal, LoginInfoDTO.class);
            return loginInfoDto;
        }catch (Exception e){
            log.error("用户登录对象获取失败");
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
    }

    //获取用户名
    public static String getLoginName(){
        try {
            //获取上下文
            SecurityContext context = SecurityContextHolder.getContext();
            if(context == null){
                return null;
            }
            Authentication authentication = context.getAuthentication();
            if(authentication == null){
                return null;
            }
            String principal = (String) authentication.getPrincipal();
            LoginInfoDTO loginInfoDto = JSON.parseObject(principal, LoginInfoDTO.class);
            return loginInfoDto.getUsername();
        }catch (Exception e){
            log.error("用户登录对象获取失败");
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
    }
}
